Web development and Tech news Blog site. WEBISFREE.com

HOME > js

[JavaScript ] Converting UTC time to current local time

Last Modified : 07 Aug, 2023 / Created : 08 Aug, 2023
548
View Count
We aim to briefly explore how to convert UTC time in JavaScript to the local time of the current visitor's location. This conversion might typically be necessary in the following scenarios:

  • The time retrieved from the server is in UTC.
  • The time to be displayed on the web is not UTC but the visitor's local time.
  • Convert and then display.


For local time conversion, most people use libraries. Here, we'll look at how to do this using "dayjs", which is one of the commonly used libraries.



# How to get local time from UTC using dayjs


First, let's assume the time retrieved from the server through an API is as follows:
let utcTime = '2023-07-31T12:00:00Z';

Now, we need to convert the aforementioned time using dayjs. For this purpose, dayjs provides an extension plugin named dayjs-plugin-utc that can handle UTC times. You can use it as shown below with the extend() method.
const dayjs = require('dayjs');
const utc = require('dayjs-plugin-utc');

dayjs.extend(utc);

With this, it has now become possible to convert using UTC to the desired local time. We apply the above utcTime variable and utilize the local() method to retrieve the local time.
// Set UTC time to dayjs
let utcDate = dayjs.utc(utcTime);

// Switch UTC time to local time with local() method
let localTime = utcDate.local();

// Print with console.log
console.log(localTime);

Now, if you check the console output, you can obtain the converted local time. Typically, one wouldn't use it as is, but would adjust to a desired format. In reality, you might use it as shown below. The following demonstrates how to display it in the year-month-day hour:minute:second format.
let localTime = utcDate.local().format('YYYY-MM-DD HH:mm:ss');

This allows you to display in a variety of formats.


So far, we have briefly looked at how to obtain local time using dayjs().
Perhaps you're looking for the following text as well?

    Previous

    [JavaScript] How to set the maximum length of an array

    Previous

    Setting Specific Range of Node or NPM version in package.json